<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Setting extends Model
{
    protected $table = 'ims_yz_setting';
    
    public $timestamps = false;
    
    protected $guarded = [''];
    
    protected $fillable = ['uniacid', 'group', 'key', 'value', 'type'];
    
    /**
     * 获取配置值
     * 
     * @param string $key 配置键名，格式：group.key 或 group.key.subkey
     * @param mixed $default 默认值
     * @param int $uniacid 公众号ID，默认为1
     * @return mixed
     */
    public static function get($key, $default = null, $uniacid = 1)
    {
        // 缓存键
        $cacheKey = "setting:{$uniacid}:{$key}";
        
        // 尝试从缓存获取
        if (Cache::has($cacheKey)) {
            return Cache::get($cacheKey);
        }
        
        // 解析键名：plugin.store => group='plugin', key='store'
        list($group, $itemKey) = self::parseKey($key);
        
        // 如果没有子键，获取整个组的配置
        if (empty($itemKey)) {
            $value = self::getGroupItems($uniacid, $group);
        } else {
            // 获取特定键的值
            $groupItems = self::getGroupItems($uniacid, $group);
            
            // 支持多级键：store.withdraw_mode
            $value = self::getNestedValue($groupItems, $itemKey, $default);
        }
        
        // 如果没有找到值，返回默认值
        if ($value === null || $value === []) {
            $value = $default;
        }
        
        // 缓存10分钟
        Cache::put($cacheKey, $value, 600);
        
        return $value;
    }
    
    /**
     * 设置配置值
     * 
     * @param string $key
     * @param mixed $value
     * @param int $uniacid
     * @return bool
     */
    public static function set($key, $value, $uniacid = 1)
    {
        list($group, $itemKey) = self::parseKey($key);
        
        $type = self::getTypeOfValue($value);
        
        // 如果是数组，序列化
        if ($type === 'array') {
            $value = serialize($value);
        }
        
        // 更新或创建
        $setting = self::updateOrCreate(
            [
                'uniacid' => $uniacid,
                'group' => $group,
                'key' => $itemKey,
            ],
            [
                'value' => $value,
                'type' => $type,
            ]
        );
        
        // 清除缓存
        $cacheKey = "setting:{$uniacid}:{$key}";
        Cache::forget($cacheKey);
        
        return $setting ? true : false;
    }
    
    /**
     * 获取组内所有配置项
     * 
     * @param int $uniacid
     * @param string $group
     * @return array
     */
    protected static function getGroupItems($uniacid, $group)
    {
        $items = [];
        
        $settings = self::where('uniacid', $uniacid)
                       ->where('group', $group)
                       ->get();
        
        foreach ($settings as $setting) {
            $value = $setting->value;
            
            // 根据类型转换值
            switch (strtolower($setting->type)) {
                case 'string':
                    $value = (string)$value;
                    break;
                case 'integer':
                    $value = (int)$value;
                    break;
                case 'double':
                    $value = (float)$value;
                    break;
                case 'boolean':
                    $value = (bool)$value;
                    break;
                case 'array':
                    $value = unserialize($value);
                    break;
                case 'null':
                    $value = null;
                    break;
            }
            
            $items[$setting->key] = $value;
        }
        
        return $items;
    }
    
    /**
     * 解析配置键名
     * 
     * @param string $key
     * @return array [group, itemKey]
     */
    protected static function parseKey($key)
    {
        $parts = explode('.', $key, 2);
        
        if (count($parts) > 1) {
            return [$parts[0], $parts[1]];
        }
        
        return [$parts[0], ''];
    }
    
    /**
     * 获取嵌套值
     * 
     * @param array $data
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    protected static function getNestedValue($data, $key, $default = null)
    {
        if (isset($data[$key])) {
            return $data[$key];
        }
        
        // 支持多级键：a.b.c
        $keys = explode('.', $key);
        $value = $data;
        
        foreach ($keys as $k) {
            if (is_array($value) && isset($value[$k])) {
                $value = $value[$k];
            } else {
                return $default;
            }
        }
        
        return $value;
    }
    
    /**
     * 获取值的类型
     * 
     * @param mixed $value
     * @return string
     */
    protected static function getTypeOfValue($value)
    {
        $givenType = strtolower(gettype($value));
        
        switch ($givenType) {
            case 'string':
            case 'integer':
            case 'double':
            case 'boolean':
            case 'null':
                return $givenType;
            case 'array':
                return 'array';
            default:
                return 'string';
        }
    }
    
    /**
     * 清除所有配置缓存
     */
    public static function clearCache()
    {
        Cache::flush();
    }
}

